﻿package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;

	[SWF(width="800", height="600", fps="30", backgroundColor="#cccccc")]
	public class MD5Test extends Sprite {
		private var txt:TextField = new TextField();
		private var fr:FileReference = new FileReference();
		public function MD5Test() {
			init();
			MD5TestSuite();
		}

		private function init():void {
			txt.x = txt.y = 5;
			txt.width = stage.stageWidth - 10;
			txt.height = stage.stageHeight - 10;
			txt.border = true;
			txt.doubleClickEnabled = true;
			txt.defaultTextFormat = new TextFormat("_typewriter");
			txt.alwaysShowSelection = true;
			txt.addEventListener(MouseEvent.DOUBLE_CLICK, onClick);
			addChild(txt);
		}
		private function onClick(evt:MouseEvent):void {
			fr.addEventListener(Event.SELECT, onFileSelect);
			fr.browse();
		}
		private function onFileSelect(evt:Event):void {
			fr.removeEventListener(Event.SELECT, onFileSelect);
			fr.addEventListener(Event.COMPLETE, onFileLoad);
			fr.load();
		}
		private function onFileLoad(evt:Event):void {
			fr.removeEventListener(Event.COMPLETE, onFileLoad);
			var stt:int = getTimer();
			MD5File(fr.data, fr.name);
			print(getTimer() - stt + " ms\n");
		}

		/* Digests a string and prints the result.
		 */
		private function MD5String (string:String):void {
			var bytes:ByteArray = new ByteArray();
			bytes.writeUTFBytes(string);
			print ("MD5 (\"" + string + "\") = " + MD5(bytes) + '\n');
		}

		/* Digests a reference suite of strings and prints the results.
		 */
		private function MD5TestSuite ():void {
			print ("MD5 test suite:\n");

			var stt:int = getTimer();

			MD5String ("");
			MD5String ("a");
			MD5String ("abc");
			MD5String ("message digest");
			MD5String ("abcdefghijklmnopqrstuvwxyz");
			MD5String ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
			MD5String ("12345678901234567890123456789012345678901234567890123456789012345678901234567890");

			print(getTimer() - stt + " ms\n");
		}

		/* Digests a file and prints the result.
		*/
		private function MD5File (file:ByteArray, name:String):void {
			print("MD5 (" + name + ") = " + MD5(file) + '\n');
		}

		private function print(str:String):void {
			txt.appendText(str);
		}
	}
}
